import { onMounted, onUnmounted } from "vue";
import { useData } from "@table/hooks/useData";
export const useTable = () => {
  const { api, searchOptions, pagination, options, eventBus, tableData, afterApiTransformData } = useData(); // tableData

  const getTableData = async () => {
    if (!api) return;
    let params: any = {};
    if (!options.value.searchSetting?.isSearchRange) {
      const clone = JSON.parse(JSON.stringify(searchOptions.value));
      delete clone.keywordRange;
      params = { ...clone };
    } else {
      params = { ...searchOptions.value };
    }
    if (pagination?.value) {
      params.currentPage = pagination.value.currentPage;
      params.pageSize = pagination.value.pageSize;
    }

    try {
      if (api) {
        let { data } = await api?.(params);
        if (pagination?.value) {
          pagination.value.total = Number(data?.total);
        }
        data = data.records;
        if (afterApiTransformData) {
          data = afterApiTransformData(data);
          data = data.map((item: any, index: number) => {
            item.dataIndex = index + 1;
            return item;
          });
        }
        tableData.value = data || [];
        eventBus.emit("fixedStyle");
      }
    } catch (error) {
      console.log(error);
    }
    // tableData?.value = data.list;
  };

  onUnmounted(() => {
    eventBus.off("refresh");
  });
  onMounted(() => {
    getTableData();

    eventBus.on("refresh", getTableData);
  });

  return {
    getTableData
  };
};
